<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            overflow: hidden;
        }
    </style>
</head>

<body>
    <canvas id="dotCanvas"></canvas>
    <script>
        // 获取画布和画笔
        var canvas = document.querySelector("#dotCanvas")
        var ctx = canvas.getContext("2d");

        // 定义点的个数和半径
        var count = 100;
        var dotradios = 5;

        // 定义保存点的数组
        var dots = [];

        //  设置canvas宽高
        // canvas.setAttribute("width", innerWidth);
        // canvas.setAttribute("height", innerHeight);

        // 快捷设置宽高
        canvas.width = innerWidth;
        canvas.height = innerHeight;

        // 随机点绘制：点就是一个圆
        for (var i = 0; i < count; i++) {
            ctx.beginPath();
            // 随机点的圆心坐标
            var random_x = parseInt(Math.random() * canvas.width);
            var random_y = parseInt(Math.random() * canvas.height);
            // 随机点的速度，随机-1 1 x和y轴速度独立
            var randomArr = [1, -1];
            var random_speedX = randomArr[parseInt(Math.random() * 2)];
            var random_speedY = randomArr[parseInt(Math.random() * 2)];
            // 勾勒圆
            ctx.arc(random_x, random_y, dotradios, 0, 2 * Math.PI);
            ctx.closePath();
            ctx.fillStyle = "pink";
            ctx.fill();

            // 把点的信息保存在对象中，并把对象放在数组中
            var dot = {
                x: random_x,
                y: random_y,
                speedX: random_speedX,
                speedY: random_speedY
            };
            // 放入数组
            dots.push(dot);
        }

        // 随机移动
        // 每个点用一个原生对象来保存，圆心坐标
        // 改变点的圆心位置，比如在原来的基础上-4
        setInterval(function () {
            // 先清屏再绘制
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            for (var i = 0; i < dots.length; i++) {
                var dot = dots[i];
                dot.x -= dot.speedX;
                dot.y -= dot.speedY;

                // 需要把更新后的圆心坐标更新到画布中，重新绘制点
                ctx.beginPath();
                ctx.arc(dot.x, dot.y, dotradios, 0, 2 * Math.PI);
                ctx.closePath();
                ctx.fillStyle = "pink";
                ctx.fill();

                // 如果超出画布范围，则速度取反
                if (dot.x < 0 || dot.x > parseInt(canvas.width)) {
                    dot.speedX *= -1;
                }
                if (dot.y < 0 || dot.y > parseInt(canvas.height)) {
                    dot.speedY *= -1;
                }
            }


        }, 70)

        

    </script>
</body>

</html>